package com.tanhua.sso.controller;

import com.tanhua.sso.pojo.User;
import com.tanhua.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> param) throws Exception {
        String mobile = param.get("phone");
        String code = param.get("verificationCode");
        String data = this.userService.login(mobile, code);
        Map<String, Object> result = new HashMap<>(2);

        if (StringUtils.isNotEmpty(data)) {
            //登录成功
            String[] ss = StringUtils.split(data, '|');
            result.put("token", ss[0]);
            result.put("isNew", Boolean.valueOf(ss[1]));
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 根据token查询用户数据
     */
    @GetMapping("{token}")
    public ResponseEntity<User> queryUserByToken(@PathVariable("token") String token) throws IOException {
        User user = this.userService.queryUserByToken(token);
        return ResponseEntity.ok(user);
    }
}
